/*
 * Copyrignt (c) qkier.com. All Rights Reserved.
 * Author: xuzeshui@qkier.com
 * Created Time: 2017-04-21 17:31:02
 * Last Modified: 2017-04-21 21:41:31
 * File Name: controllers/location.go
 * Description:
 */

//
package controllers

import (
	"openapi/errorcode"
	"openapi/geo/geoaddr"
	"openapi/ip"

	log "github.com/cihub/seelog"
)

type LocationController struct {
	BaseController
}

//综合定位
// @router /location [get]
func (p *LocationController) Location() {
	defer p.Output("Location")
	lat, _ := p.GetFloat("lat", 0.0)
	lng, _ := p.GetFloat("lng", 0.0)
	coordType := p.GetString("coord_type", "wgs84ll")
	loc, _ := p.GetInt("loc", 3)
	var gitem *geoaddr.GeoHashAddrItem

	p.Resp["loc"] = 1 //默认从坐标
	if loc&0x1 == 0x1 {
		gitem = geoaddr.QueryGeoAddr(lat, lng, coordType)
	}
	if loc&0x2 == 0x2 && gitem == nil {
		clientIP := p.Ctx.Input.IP()
		log.Infof("location by clientip: %s, lat: %f, lng: %f, coord_type: %s, loc: %d", clientIP, lat, lng, coordType, loc)
		if ipItem := ip.IPLocation(clientIP); ipItem != nil {
			gitem = &geoaddr.GeoHashAddrItem{}
			gitem.RegionCode = ipItem.RegionCode
			gitem.AddrFormat = ipItem.Country + ipItem.Province + ipItem.City + ipItem.County
			p.Resp["loc"] = 2 //从IP获取
		}

	}
	if gitem == nil {
		p.Resp["code"] = errorcode.EC_LOCATION_NOT_FOUND
		p.Resp["msg"] = "无法获取任何定位结果"
		p.Resp["loc"] = 0 //都没有获取
	} else {
		p.Resp["data"] = gitem
		p.Resp["code"] = errorcode.EC_GL_SUCCESS
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_SUCCESS)
	}
}
